package com.xiaowei.gym.gymjsp.ware.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.xiaowei.gym.gymjsp.ware.dao.AdminDao;
import com.xiaowei.gym.gymjsp.ware.dao.impl.AdminDaoImpl;
import com.xiaowei.gym.gymjsp.ware.dto.AdminDTO;
import com.xiaowei.gym.gymjsp.ware.entity.AdminEntity;
import com.xiaowei.gym.gymjsp.ware.service.AdminService;
import com.xiaowei.gym.gymjsp.ware.vo.AdminVo;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

public class AdminServiceImpl implements AdminService{

    private AdminDao adminDao;

    public AdminServiceImpl() {
      adminDao = new AdminDaoImpl();
    }

    @Override
    public int createAdmin(AdminEntity adminEntity) {
        return adminDao.createAdmin(adminEntity);
    }

    @Override
    public AdminEntity getAdminById(Integer id) {
        return adminDao.getAdminById(id);
    }

    @Override
    public AdminEntity getAdminByAdminname(String username) throws SQLException {
        return null;
    }

    @Override
    public boolean verifyPassword(AdminEntity adminEntity, String password) throws NoSuchAlgorithmException {
        return false;
    }

    @Override
    public int getAdminCount() {
        int adminCount = adminDao.getAdminCount();
        return adminCount;
    }

    @Override
    public AdminEntity validate(String username, String password) {
        return adminDao.validate(username,password);
    }

    @Override
    public List<AdminEntity> getAdminList(String queryUserName, int currentPageNo, int pageSize) {
        return adminDao.getAdminList(queryUserName,currentPageNo,pageSize);
    }

    @Override
    public boolean deleteAdminByIds(Integer[] delId) {
        int[] i = adminDao.deleteAdminByIds(delId);
        if (i != null){
            return true;
        }else {
            return false;
        }

    }

    @Override
    public boolean modify(AdminEntity adminEntity) {
        Integer modify = adminDao.modify(adminEntity);
        if (modify > 0){
            return true;
        }else {
            return false;
        }

    }

    @Override
    public Map<String, Object> validAdmin(AdminDTO adminDTO) {
        Map<String, Object> map = adminDao.validAdmin(adminDTO);
        return map;
    }

    @Override
    public List<AdminVo> exportExcel(HttpServletResponse response) throws IOException {
        List<AdminVo> adminVoList =null;
        ExcelWriter excelWriter = null;
        OutputStream outputStream = null;
        WriteSheet writeSheet;
        try {
            outputStream=response.getOutputStream();
            excelWriter = EasyExcel.write(outputStream,AdminVo.class).build();
            // 分页查询person表中的记录并将查询结果写入Excel文件
            int pageSize = 10; // 每页查询的数量
            int pageNum = 1; // 当前页码
            //TODO 这里可以考虑如果一个sheet的记录太多时，可以分多个sheet读取，移到while循环中即可
            writeSheet = EasyExcel.writerSheet(pageNum - 1, "管理员基本信息表").build();
            while (true) {
//                writeSheet = EasyExcel.writerSheet(pageNum - 1, "人员基本信息表"+pageNum).build();
                int offset = (pageNum - 1) * pageSize;
                adminVoList =  adminDao.selectByPage(offset, pageSize);
                if (adminVoList.isEmpty()) {
                    // 设置响应头
                    // 设置文本内省
                    response.setContentType("application/vnd.ms-excel");
                    // 设置字符编码
                    response.setCharacterEncoding("utf-8");
                    response.setHeader("Content-disposition", "attachment;filename="+getBirthday()+".xlsx");
                    break;
                }
                excelWriter.write(adminVoList, writeSheet);
                pageNum++;
            }
        }catch (Exception e){
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            e.printStackTrace();
        }finally {
            outputStream.flush();
            excelWriter.close();
            outputStream.close();
        }
        return adminVoList;
    }


    @Override
    public Integer batchInsert(List<AdminDTO> t) {
        if (t.size() > 0 || !t.isEmpty()){
            t.forEach(adminDTO -> {
                AdminEntity adminEntity = new AdminEntity();
                adminEntity.setUsername(adminDTO.getName());
                adminEntity.setPhone(adminDTO.getPhone());
                adminEntity.setEmail(adminDTO.getEmail());
                adminDao.createAdmin(adminEntity);
            });
            return 1;
        }
        return 0;
    }

    //格式化文件名，按照系统时间命名
    private String getBirthday(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        String ExcelName = simpleDateFormat.format(System.currentTimeMillis());
        return ExcelName;
    }
}
